2611. Replace digit

 

Given a number n and two digits a and b. Replace every occurrence of digit a in n with digit b.

 

Input. Three integers n (1 ≤ n ≤ 109), a, b (0 ≤ a, b9).

 

Output. Print the resulting number after the replacements. Leading zeros should not be included in the output.

 

Sample input

Sample output

123118 1 5

523558

 

 

SOLUTION

strings

 

Algorithm analysis

Read the number n as a string and the digits a and b as characters. Replace all occurrences of character a in the string n with character b. Then print the resulting string, removing any leading zeros. If the final string consists only of zeros, print a single zero.

The resulting number may exceed the range of the int type. For example, if n = 1000000000 (109), a = 1, b = 9, the result will be 9000000000 (9 * 109).

 

Algorithm implementation

Store the number n as a string in the array s.

 

char s[100];

 

Read the number n as a string and the digits a and b as characters.

 

scanf("%s %c %c",s,&a,&b);

 

Replace all occurrences of character a with character b in the string s.

 

for (i = 0; i < strlen(s); i++)

  if (s[i] == a) s[i] = b;

 

Convert the string s into a number res of type long long.

 

res = atoll(s);

 

Print the answer.

 

printf("%lld\n", res);

 

Algorithm implementation – string

Read the number n as a string and the digits a and b as characters.

 

cin >> s >> a >> b;

 

Replace all occurrences of character a with character b in the string s.

 

replace(s.begin(), s.end(), a, b);

 

Convert the string s into a number res of type long long.

 

res = stoll(s);

 

Print the answer.

 

cout << res << endl;

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    String s = con.next();

    char a = con.next().charAt(0);

    char b = con.next().charAt(0);

    s = s.replace(a,b);

 

    int flag = 0;

    for(int i = 0; i < s.length(); i++)

    if (s.charAt(i) != '0')

    {

      s = s.substring(i);

      flag = 1;

      break;

    }

    if (flag == 0) s = "0";

    System.out.println(s);

    con.close();

  }

}

 

Python implementation

Read the input data as strings.

 

s, a, b = input().split()

 

Replace all occurrences of character a with character b in the string s.

 

s = s.replace(a, b)

 

Convert the string s into an integer and print the result.

 

print(int(s))